﻿using Furion;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IndoorPosition.Server.Core.Utils
{
    /// <summary>
    /// 文件上传下载工作类
    /// </summary>
    public static class FileUtil
    {
        /// <summary>
        /// 获取文件流
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static FileStream GetStream(string fileName, string flag)
        {
            var root = App.WebHostEnvironment.WebRootPath != null ? App.WebHostEnvironment.WebRootPath : App.WebHostEnvironment.ContentRootPath;
            var filePath = Path.Combine(root, "file", flag, fileName);
            return new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
        }

        /// <summary>
        /// 保存文件
        /// </summary>
        /// <param name="file"></param>
        /// <param name="flag"></param>
        /// <returns></returns>
        public async static Task<string> SaveFileAsync(IFormFile file, string flag)
        {
            var root = App.WebHostEnvironment.WebRootPath != null ? App.WebHostEnvironment.WebRootPath : App.WebHostEnvironment.ContentRootPath;
            var filePath = Path.Combine(root, "file", flag);
            if (!Directory.Exists(filePath))
                Directory.CreateDirectory(filePath);

            var fileSuffix = Path.GetExtension(file.FileName).ToLower(); // 文件后缀

            var finalName = Guid.NewGuid().ToString("N") + fileSuffix; // 生成文件的最终名称
            using (var stream = File.Create(Path.Combine(filePath, finalName)))
            {
                await file.CopyToAsync(stream);
            }

            return finalName;
        }
    }
}
